<template>
  <div>
    <v-viewer ref="view"></v-viewer>
    <el-form size="medium"
             label-position="right"
             label-width="100px">
      <el-form-item label="客户">
        <el-select v-model="customer.id"
                   filterable
                   placeholder="请选择客户"
                   @change="setCustomerDetail(customer.id)">
          <el-option v-for="(item, key) in customerList"
                     :key="key"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户姓名">
        <el-col :span="7">
          <el-input v-model="customer.customerName"
                    placeholder="客户姓名"
                    size="medium"></el-input>
        </el-col>
        <el-col :span="10">
          <el-form-item label="性别">
            <el-radio v-model="customer.gender"
                      border
                      label='男'>男</el-radio>
            <el-radio v-model="customer.gender"
                      border
                      label='女'>女</el-radio>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="客户手机号">
        <el-col :span="7">
          <el-input v-model.number="customer.customerTel"
                    placeholder="客户手机号"
                    size="medium"></el-input>
        </el-col>
        <el-col :span="10">
          <el-form-item label="客户地址">
            <el-input v-model="customer.address"
                      placeholder="客户地址"
                      size="medium"></el-input>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="客户来源">
        <el-col :span="7">
          <el-input v-model="customer.customerSource"
                    placeholder="客户来源"
                    size="medium"></el-input>
        </el-col>
        <el-col :span="10">
          <el-form-item label="客户邮箱">
            <el-input v-model="customer.email"
                      placeholder="客户邮箱"
                      size="medium"></el-input>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="合同金额">
        <el-col :span="7">
          <el-input v-model.number="orderAmount"
                    placeholder="合同金额"
                    @change="() => {finCost = (orderAmount || 0) - (customerPay || 0)}"
                    size="medium"></el-input>
        </el-col>
        <el-col :span="10">
          <el-form-item label="客户付款">
            <el-input v-model.number="customerPay"
                      placeholder="客户付款"
                      @change="() => {finCost = (orderAmount || 0) - (customerPay || 0)}"
                      size="medium"></el-input>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="客户尾款">
        <el-col :span="7">
          <el-input v-model.number="finCost"
                    placeholder="客户尾款"
                    size="medium"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="签约时间">
        <el-col :span="7">
          <el-date-picker v-model="order.signedTime"
                          type="date"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          placeholder="签约时间">
          </el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="合同截至日">
        <el-col :span="7">
          <el-date-picker v-model="order.endedTime"
                          type="date"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          placeholder="合同截至日">
          </el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="尾款支付方式">
        <el-radio v-model="order.finCostType"
                  border
                  label=0>配送前</el-radio>
        <el-radio v-model="order.finCostType"
                  border
                  label=1>配送后</el-radio>
      </el-form-item>
      <el-form-item label="客户合同">
        <span style="color:red;"
              v-if="order.contractStatus==1">不通过理由：{{ order.contractRemark }}</span>
        <pic-view :file-list="order.contractUrlList"
                  upload-class="short-upload"
                  :pic-name-list.sync="order.contractNameList"
                  :max-size="5"
                  :upload-data="{ fileName: 'contract' }"
                  @showImg="showImg"></pic-view>
      </el-form-item>
      <el-form-item label="客户收支证明">
        <span style="color:red;"
              v-if="order.incomeStatus==1">不通过理由：{{ order.incomeRemark }}</span>
        <pic-view :file-list="order.incomeUrlList"
                  upload-class="short-upload"
                  :pic-name-list.sync="order.incomeNameList"
                  :max-size="5"
                  :upload-data="{ fileName: 'income' }"
                  @showImg="showImg"></pic-view>
      </el-form-item>
      <el-form-item label="货物详细">
        <el-upload :action="uploadExcelAction"
                   :on-preview="handlePreview"
                   :on-remove="handleRemove"
                   multiple
                   :limit="1"
                   :headers="{ Authorization: getToken() }"
                   :on-exceed="handleExceed"
                   :on-success="uploadSuccess"
                   :file-list="order.fileList">
          <el-button size="small"
                     type="primary">点击上传货物Excel</el-button>
          <span style="color:red;"
                v-if="childOrders.some(a => a.status === 3)">不通过理由：{{ childOrders.map(a => a.remark).join('，') }}</span>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-row>
          <el-col :span="24">
            <div class="el-table-total"><span>合同金额&nbsp;{{ order.totalAmount | total(childOrders.map(a => a.totalMoney || 0)) }}</span></div>
          </el-col>
          <el-col :span="24">
            <el-table ref="multipleTable"
                      border
                      :data="childOrders"
                      class="tb-edit"
                      highlight-current-row
                      style="width: 100%"
                      @row-click="handleCurrentChange">
              <el-table-column label="编号"
                               width="80">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model="scope.row.itemNo"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.itemNo}}</span>
                </template>
              </el-table-column>
              <el-table-column label="区域">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model="scope.row.area"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.area}}</span>
                </template>
              </el-table-column>
              <el-table-column label="品名"
                               width="80">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model="scope.row.productName"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.productName}}</span>
                </template>
              </el-table-column>
              <el-table-column label="品牌"
                               width="80">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model="scope.row.brandName"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.brandName}}</span>
                </template>
              </el-table-column>
              <el-table-column label="产品型号">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model="scope.row.sku"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.sku}}</span>
                </template>
              </el-table-column>
              <el-table-column label="官网截图"
                               width="130">
                <template slot-scope="scope">
                  <pic-view :file-list="scope.row.officialUrlList"
                            upload-class="small-upload"
                            :pic-name-list.sync="scope.row.officialNameList"
                            :max-size="2"
                            :upload-data="{ fileName: 'official' }"
                            @showImg="showImg"></pic-view>
                </template>
              </el-table-column>
              <el-table-column label="产品图片"
                               width="130">
                <template slot-scope="scope">
                  <pic-view :file-list="scope.row.productUrlList"
                            upload-class="small-upload"
                            :pic-name-list.sync="scope.row.productNameList"
                            :max-size="2"
                            :upload-data="{ fileName: 'product' }"
                            @showImg="showImg"></pic-view>
                </template>
              </el-table-column>
              <el-table-column label="尺寸">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model="scope.row.size"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.size}}</span>
                </template>
              </el-table-column>
              <el-table-column label="主面料"
                               width="130">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model="scope.row.mainFabric"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.mainFabric}}</span>
                  <pic-view :file-list="scope.row.bodyUrlList"
                            upload-class="small-upload"
                            :pic-name-list.sync="scope.row.bodyNameList"
                            :max-size="2"
                            :upload-data="{ fileName: 'product' }"
                            @showImg="showImg"></pic-view>
                </template>
              </el-table-column>
              <el-table-column label="抱枕面料"
                               width="130">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model="scope.row.bolsterFabric"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.bolsterFabric}}</span>
                  <pic-view :file-list="scope.row.pillowUrlList"
                            upload-class="small-upload"
                            :pic-name-list.sync="scope.row.pillowNameList"
                            :max-size="2"
                            :upload-data="{ fileName: 'product' }"
                            @showImg="showImg"></pic-view>
                </template>
              </el-table-column>
              <el-table-column label="木质部分材质"
                               width="130">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model="scope.row.woodTexture"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.woodTexture}}</span>
                  <pic-view :file-list="scope.row.woodenUrlList"
                            upload-class="small-upload"
                            :pic-name-list.sync="scope.row.woodenNameList"
                            :max-size="2"
                            :upload-data="{ fileName: 'product' }"
                            @showImg="showImg"></pic-view>
                </template>
              </el-table-column>
              <el-table-column label="其他材质备注"
                               width="130">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model="scope.row.otherTexture"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.otherTexture}}</span>
                  <pic-view :file-list="scope.row.otherUrlList"
                            upload-class="small-upload"
                            :pic-name-list.sync="scope.row.otherNameList"
                            :max-size="2"
                            :upload-data="{ fileName: 'product' }"
                            @showImg="showImg"></pic-view>
                </template>
              </el-table-column>
              <el-table-column label="订货数量"
                               width="60">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model.number="scope.row.quantity"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.quantity}}</span>
                </template>
              </el-table-column>
              <el-table-column label="单价">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model.number="scope.row.price"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>￥{{scope.row.price}}</span>
                </template>
              </el-table-column>
              <el-table-column label="总价">
                <template slot-scope="scope">
                  <el-input size="small"
                            v-model.number="scope.row.totalMoney"
                            placeholder=""
                            @change="handleEdit(scope.$index, scope.row)"></el-input> <span>￥{{scope.row.totalMoney}}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作"
                               width="80">
                <template slot-scope="scope">
                  <el-button size="small"
                             type="danger"
                             @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="24">
            <div class="el-table-add-row"
                 style="width: 99.2%;"
                 @click="addChildOrder()"><span>+ 添加</span></div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="newOrder">提交</el-button>
        <el-button @click="() => {this.$router.go(-1)}">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style>
</style>

<script>
import { getToken, getUser } from '@/utils/auth'
import '@/style/info.scss'
import picView from '@/components/pic-viewer-up'
import vViewer from '@/components/v-viewer'
import '@/style/common.scss'
import viewPage from '@/components/pagination'
import { HTTPSUCCESS, HTTPDATAFAIL, HTTPPARAMFAIL, HTTPUNKOWNFAIL } from '@/components/constant'
import { api, devBaseURL } from '@/api'
import { packageImgList } from '@/utils/imgPackage'
import { validatenull, vListLength } from '@/utils/validate'
import { total } from '@/utils/filters'

export default {
  data() {
    return {
      orderAmount: null,
      customerPay: null,
      finCost: null,
      uploadExcelAction: devBaseURL + api.CHILD_ORDER_IMPORT,
      orderId: this.$route.params.orderId || null,
      customerList: [],
      planDialog: false,
      customer: {},
      order: {},
      orderCustomerInfo: {},
      childOrders: []
    }
  },
  components: {
    picView, vViewer, viewPage
  },
  activated() {
    this.reset()
    this.getOrder()
    this.getCustomerList()
  },
  computed: {
  },
  methods: {
    getUser,
    getToken,
    total,
    reset() {
      this.orderAmount = null
      this.customerPay = null
      this.finCost = null
      this.customer = {}
      this.order = {}
      this.order.contractUrlList = []
      this.order.contractNameList = []
      this.order.incomeUrlList = []
      this.order.incomeNameList = []
      this.order.fileList = []
      this.orderCustomerInfo = {}
      this.childOrders = []
    },
    setCustomerDetail(id) {
      const info = this.customerList.filter(a => a.id === id)[0]
      this.customer = {
        id: info.id,
        customerName: info.name,
        gender: info.gender === 'MALE' ? '男' : '女',
        customerTel: info.mobilePhone,
        address: info.address,
        customerSource: info.source,
        email: info.email
      }
    },
    getCustomerList() {
      this.$http.get(api.CUSTOMER_SELECT_LIST).then(
        res => {
          if (res.error.code === HTTPSUCCESS) {
            this.customerList = res.result
          } else {
            this.$msg._message(res.error.message, 'error')
          }
        }
      )
    },
    getOrder() {
      if (!validatenull(this.orderId)) {
        this.$http.get(api.ORDER_DETAIL, { orderId: this.orderId }).then(
          res => {
            if (res.error.code === HTTPSUCCESS) {
              this.order = res.result.order
              this.customer = res.result.customer
              this.childOrders = res.result.childOrders
              this.orderAmount = this.order.orderAmount
              this.customerPay = this.order.customerPay
              this.finCost = this.order.finCost
              this.order.finCostType = this.order.finCostType + ''
              if (this.order.contract) {
                const contractList = packageImgList(this.order.contract)
                this.order.contractNameList = contractList[0]
                this.order.contractUrlList = contractList[1]
              }
              if (this.order.income) {
                const contractList = packageImgList(this.order.income)
                this.order.incomeNameList = contractList[0]
                this.order.incomeUrlList = contractList[1]
              }
              this.childOrders.forEach(e => {
                if (e.officialPicture) {
                  const officialList = packageImgList(e.officialPicture)
                  e.officialNameList = officialList[0]
                  e.officialUrlList = officialList[1]
                }
                if (e.productPicture) {
                  const productList = packageImgList(e.productPicture)
                  e.productNameList = productList[0]
                  e.productUrlList = productList[1]
                }
                if (e.mainFabricPicture) {
                  const bodyList = packageImgList(e.mainFabricPicture)
                  e.bodyNameList = [e.mainFabricPicture]
                  e.bodyUrlList = bodyList[1]
                }
                if (e.bolsterFabricPicture) {
                  const pillowList = packageImgList(e.bolsterFabricPicture)
                  e.pillowNameList = [e.bolsterFabricPicture]
                  e.pillowUrlList = pillowList[1]
                }
                if (e.woodTexturePicture) {
                  const woodenList = packageImgList(e.woodTexturePicture)
                  e.woodenNameList = [e.woodTexturePicture]
                  e.woodenUrlList = woodenList[1]
                }
                if (e.otherTexturePicture) {
                  const otherList = packageImgList(e.otherTexturePicture)
                  e.otherNameList = [e.otherTexturePicture]
                  e.otherUrlList = otherList[1]
                }
                if (e.problemPicture) {
                  const problemList = packageImgList(e.problemPicture)
                  e.problemNameList = problemList[0]
                  e.problemUrlList = problemList[1]
                }
              })
            } else {
              this.$msg._message(res.error.msg, 'error')
            }
          }
        )
      }
    },
    newOrder() {
      const user = JSON.parse(getUser())
      if (validatenull(this.customer.customerName)) return this.$msg._message('请填写客户姓名', 'warning')
      if (validatenull(this.customer.gender)) return this.$msg._message('请选择客户性别', 'warning')
      if (validatenull(this.customer.customerTel)) return this.$msg._message('请填写客户手机号', 'warning')
      if (validatenull(this.customerPay)) return this.$msg._message('请填写客户付款', 'warning')
      if (validatenull(this.finCost)) return this.$msg._message('请填写客户尾款', 'warning')
      if (validatenull(this.orderAmount)) return this.$msg._message('请填写合同金额', 'warning')
      if (validatenull(this.order.signedTime)) return this.$msg._message('请填写签约时间', 'warning')
      if (validatenull(this.order.endedTime)) return this.$msg._message('请填写合同截至日', 'warning')
      if (validatenull(this.order.finCostType)) return this.$msg._message('请选择尾款支付方式', 'warning')
      if (validatenull(this.order.contractNameList)) return this.$msg._message('请上传客户合同', 'warning')
      if (validatenull(this.order.incomeNameList)) return this.$msg._message('请上传客户收支证明', 'warning')
      const item = []
      this.childOrders.forEach(childOrder => {
        const a = {
          id: childOrder.id,
          itemNo: childOrder.itemNo,
          brandName: childOrder.brandName,
          quantity: childOrder.quantity,
          price: childOrder.price,
          totalMoney: childOrder.totalMoney,
          itemHead: [
            {
              key: 'area',
              value: childOrder.area
            },
            {
              key: 'product_name',
              value: childOrder.productName
            },
            {
              key: 'official_picture',
              value: validatenull(childOrder.officialNameList) ? null : childOrder.officialNameList.join(',')
            },
            {
              key: 'product_picture',
              value: validatenull(childOrder.productNameList) ? null : childOrder.productNameList.join(',')
            },
            {
              key: 'size',
              value: childOrder.size
            },
            {
              key: 'sku',
              value: childOrder.sku
            },
            {
              key: 'main_fabric',
              value: childOrder.mainFabric
            },
            {
              key: 'main_fabric_picture',
              value: validatenull(childOrder.bodyNameList) ? null : childOrder.bodyNameList.join(',')
            },
            {
              key: 'bolster_fabric',
              value: childOrder.bolsterFabric
            },
            {
              key: 'bolster_fabric_picture',
              value: validatenull(childOrder.pillowNameList) ? null : childOrder.pillowNameList.join(',')
            },
            {
              key: 'wood_texture',
              value: childOrder.woodTexture
            },
            {
              key: 'wood_texture_picture',
              value: validatenull(childOrder.woodenNameList) ? null : childOrder.woodenNameList.join(',')
            },
            {
              key: 'other_texture',
              value: childOrder.otherTexture
            },
            {
              key: 'other_texture_picture',
              value: validatenull(childOrder.otherNameList) ? null : childOrder.otherNameList.join(',')
            }
          ]
        }
        item.push(a)
      })
      const params = {
        id: this.orderId,
        finalPaymentType: this.order.finCostType,
        salesmanId: user.userId,
        salesmanName: user.name,
        head: [
          {
            key: 'contract_money',
            value: this.orderAmount
          },
          {
            key: 'down_payment',
            value: this.customerPay
          },
          {
            key: 'final_payment',
            value: this.finCost
          },
          {
            key: 'contract_time',
            value: this.order.signedTime
          },
          {
            key: 'end_time',
            value: this.order.endedTime
          },
          {
            key: 'contract_picture',
            value: this.order.contractNameList.join(',')
          },
          {
            key: 'income_prove_picture',
            value: this.order.incomeNameList.join(',')
          }
        ],
        customer: this.customer,
        item: item
      }
      this.$http.post(api.ORDER_EDIT, params).then(
        res => {
          if (res.error.code === HTTPSUCCESS) {
            this.$msg._message('操作成功', 'success')
            this.$router.push({
              name: 'order'
            })
          } else {
            this.$msg._message(res.error.message, 'error')
          }
        }
      )
    },
    showImg(url) {
      this.$refs.view.showImg(url)
    },
    handleRemove(file, fileList) {
      // 删除钩子
    },
    handlePreview(file) {
      // 预览钩子
    },
    beforeUpload(file) {
      // 上传前的钩子
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    uploadSuccess(response) {
      // 上传成功的回调函数
      if (response.error.code === HTTPSUCCESS) {
        this.$msg._message('上传成功', 'success')
        response.result.forEach(e => {
          if (e.officialPicture) {
            const officialList = packageImgList(e.officialPicture)
            e.officialNameList = [e.officialPicture]
            e.officialUrlList = officialList[1]
          }
          if (e.productPicture) {
            const productList = packageImgList(e.productPicture)
            e.productNameList = [e.productPicture]
            e.productUrlList = productList[1]
          }
          if (e.mainFabricPicture) {
            const bodyList = packageImgList(e.mainFabricPicture)
            e.bodyNameList = [e.mainFabricPicture]
            e.bodyUrlList = bodyList[1]
          }
          if (e.bolsterFabricPicture) {
            const pillowList = packageImgList(e.bolsterFabricPicture)
            e.pillowNameList = [e.bolsterFabricPicture]
            e.pillowUrlList = pillowList[1]
          }
          if (e.woodTexturePicture) {
            const woodenList = packageImgList(e.woodTexturePicture)
            e.woodenNameList = [e.woodTexturePicture]
            e.woodenUrlList = woodenList[1]
          }
          if (e.otherTexturePicture) {
            const otherList = packageImgList(e.otherTexturePicture)
            e.otherNameList = [e.otherTexturePicture]
            e.otherUrlList = otherList[1]
          }
        })
        this.childOrders = response.result
      }
    },
    handleCurrentChange(row, event, column) {
      // 当前表格改变钩子
    },
    handleEdit(index, row) {
      if (!validatenull(row.quantity) && !validatenull(row.price)) {
        row.totalMoney = row.quantity * row.price
      }
    },
    handleDelete(index, row) {
      this.childOrders.splice(index, 1)
    },
    addChildOrder() {
      this.childOrders.push({})
    }
  }
}
</script>
